package com.ggs.starbug.config.rabbitmq;

import com.google.common.collect.Maps;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static com.ggs.starbug.config.rabbitmq.RabbitMQConstants.*;

/**
 * @Author lianghaohui
 * @Date 2021/12/29 14:06
 * @Description 死信队列、交换机配置
 */
@Configuration
public class DeadLetterExchangeQueueConfig {

    @Bean
    public Exchange deadLetterExchange() {
        return ExchangeBuilder.directExchange(DEAD_LETTER_EXCHANGE).durable(true).build();
    }

    @Bean
    public Exchange normalExchange() {
        return ExchangeBuilder.directExchange(NORMAL_EXCHANGE).durable(true).build();
    }

    @Bean
    public Queue queueB() {
        Map<String, Object> arguments = Maps.newHashMap();
        //设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        //设置ttl该队列的ttl时间，单位：ms  如果消息在队列中超过ttl时间没有被消费，就会进入死信交换机
//        arguments.put("x-message-ttl", 20000);  //队列与消息同时设置超时时间，则以队列的超时时间为准

        return QueueBuilder.durable(QUEUE_B).withArguments(arguments).build();
    }

    @Bean
    public Queue queueA() {
        Map<String, Object> arguments = Maps.newHashMap();
        //设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        //设置ttl该队列的ttl时间，单位：ms  如果消息在队列中超过ttl时间没有被消费，就会进入死信交换机
//        arguments.put("x-message-ttl", 20000);  //队列与消息同时设置超时时间，则以队列的超时时间为准

        return QueueBuilder.durable(QUEUE_A).withArguments(arguments).build();
    }

    @Bean
    public Queue deadLetterQueue() {
        return QueueBuilder.durable(DEAD_LETTER_QUEUE).build();
    }

    @Bean
    public Binding queueABindingNormalExchange(Queue queueA, Exchange normalExchange) {
        return BindingBuilder.bind(queueA).to(normalExchange).with(NORMAL_ROUTING_KEY_A).noargs();
    }

    @Bean
    public Binding queueBBindingNormalExchange(Queue queueB, Exchange normalExchange) {
        return BindingBuilder.bind(queueB).to(normalExchange).with(NORMAL_ROUTING_KEY_B).noargs();
    }

    @Bean
    public Binding deadLetterQueueBindingDeadLetterExchange(Queue deadLetterQueue, Exchange deadLetterExchange) {
        return BindingBuilder.bind(deadLetterQueue).to(deadLetterExchange).with(DEAD_LETTER_ROUTING_KEY).noargs();
    }

}
